#include <vector>
#include <functional>

using namespace std;

class Solution {
public:
    vector<vector<char>> updateBoard(vector<vector<char>>& board, vector<int>& click) {
        int m = board.size();
        int n = board[0].size();
        int r = click[0], c = click[1];
        if (board[r][c] == 'M') {
            board[r][c] = 'X';
            return board;
        }
        vector<pair<int, int>> dirs = {
            {-1, -1}, {-1, 0}, {-1, 1},
            {0, -1},           {0, 1},
            {1, -1},  {1, 0},  {1, 1}
        };
        auto countMines = [&](int x, int y) {
            int count = 0;
            for (auto& dir : dirs) {
                int nx = x + dir.first;
                int ny = y + dir.second;
                if (nx >= 0 && nx < m && ny >= 0 && ny < n && board[nx][ny] == 'M') {
                    count++;
                }
            }
            return count;
            };
        function<void(int, int)> dfs = [&](int x, int y) {
            if (board[x][y] != 'E') return;
            int mines = countMines(x, y);
            if (mines > 0) {
                board[x][y] = '0' + mines;
            }
            else {
                board[x][y] = 'B';
                for (auto& dir : dirs) {
                    int nx = x + dir.first;
                    int ny = y + dir.second;
                    if (nx >= 0 && nx < m && ny >= 0 && ny < n) {
                        dfs(nx, ny);
                    }
                }
            }
            };
        dfs(r, c);
        return board;
    }
};